package com.liuli.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;

//返回json类型数据
public class ReturnJson {

	public static void reponse(String json) {

		HttpServletResponse response = ServletActionContext.getResponse();
		/*
		 * 在调用getWriter之前未设置编码(既调用setContentType或者setCharacterEncoding方法设置编码),
		 * HttpServletResponse则会返回一个用默认的编码(既ISO-8859-1)编码的PrintWriter实例。这样就会
		 * 造成中文乱码。而且设置编码时必须在调用getWriter之前设置,不然是无效的。
		 */
		response.setContentType("text/html;charset=utf-8");
		// response.setCharacterEncoding("UTF-8");
		PrintWriter out;
		try {
			out = response.getWriter();
			out.println(json);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static boolean checkToken(String token) {
		Properties ps = new Properties();
		@SuppressWarnings("deprecation")
		String contextPath = ServletActionContext.getRequest().getRealPath(
				"/WEB-INF/classes");

		try {
			InputStream is = new FileInputStream(contextPath
					+ "/validate.properties");
			ps.load(is);
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (token == null || !token.equals(ps.getProperty("token"))) {
			ReturnJson.getStatus("40008");
			return false;
		}
		return true;
	}

	public static String getValue(String key) {
		Properties ps = new Properties();
		@SuppressWarnings("deprecation")
		String contextPath = ServletActionContext.getRequest().getRealPath(
				"/WEB-INF/classes");

		try {
			InputStream is = new FileInputStream(contextPath
					+ "/validate.properties");
			ps.load(is);
		} catch (IOException e) {
			e.printStackTrace();
		}

		String value = ps.getProperty(key);
		return value;
	}

	// 得到响应状态
	public static void getStatus(String errcode) {

		Properties ps = new Properties();
		@SuppressWarnings("deprecation")
		String contextPath = ServletActionContext.getRequest().getRealPath(
				"/WEB-INF/classes");

		try {
			InputStream is = new FileInputStream(contextPath
					+ "/status.properties");
			ps.load(is);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		JSONObject result = new JSONObject();
		result.put("errcode", errcode);
		result.put("errmsg", ps.getProperty(errcode));
		ReturnJson.reponse(result.toString());
	}
}
